package models

import (
	"cvevulner/common"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

func QueryOriginCveE(prcnum int) ([]OriginUpstream, int64, error) {
	o := orm.NewOrm()
	var os []OriginUpstream
	num, err := o.Raw("select cve_id,cve_un_ids,cve_num, update_type,cve_packname,"+
		"git_packname,cve_title,affect_porduct,cnnvd_id,cnvd_id,published_date,vul_status,cve_status,version"+
		" from cve_origin_upstream where cve_status in (?, ?) and is_exit = ? "+
		"order by cve_id asc limit ?", 0, 1, 2, prcnum).QueryRows(&os)
	if err == nil && num > 0 {
		logs.Info("cve_origin_upstream, Number of items found: ", num)
	} else {
		logs.Info("QueryOriginCveE, There is currently no new or updated cve, cur_time:",
			common.GetCurTime(), ", err: ", err)
	}
	return os, num, err
}

func UpdateOriginExist(updatetime, pakName, version string, cveId int64, isExit int) (bool) {
	o := orm.NewOrm()
	res, err := o.Raw("UPDATE cve_origin_upstream SET "+
		"is_exit = ?, update_time = ? where cve_id = ? and git_packname = ? and version = ?",
		isExit, updatetime, cveId, pakName, version).Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		if num > 0 {
			logs.Info("cve_origin_upstream row affected nums: ", num,
				",cveId: ", cveId, ",", updatetime, pakName, version)
			return true
		}
		return false
	} else {
		logs.Error("UpdateOriginExist, Status update failed, cveId: ",
			cveId, ",", updatetime, pakName, version, ", err: ", err)
		return false
	}
}

func UpdateOriginExistTemp() (bool) {
	o := orm.NewOrm()
	res, err := o.Raw("UPDATE cve_origin_upstream SET "+
		"is_exit = ? where is_exit = ?", 2, 0).Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		if num > 0 {
			logs.Info("cve_origin_upstream row affected nums: ", num)
			return true
		}
		return false
	} else {
		logs.Error("UpdateOriginExistTemp, Update failed, err: ", err)
		return false
	}
}

// Query abnormal cve data
func QueryAbnCve(cveSt, days string, prcnum int, cveId int64) ([]VulnCenter, error) {
	o := orm.NewOrm()
	var vc []VulnCenter
	cveSql := fmt.Sprintf("select * from cve_vuln_center where "+
		"update_time >= '%s' and cve_id > %d and cve_status in (%s) "+
		"order by cve_id asc limit %d", days, cveId, cveSt, prcnum)
	logs.Info("cveSql: ", cveSql)
	num, err := o.Raw(cveSql).QueryRows(&vc)
	if err == nil && num > 0 {
		return vc, err
	}
	return vc, err
}
